package com.geek.water.controller;

import com.geek.water.constant.CodeConstant;
import com.geek.water.entity.GlobalWaterPriceTier;
import com.geek.water.result.Result;
import com.geek.water.service.GlobalWaterPriceTierService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 全局阶梯水费配置控制器
 * @author yangwenqi
 * @date 2025/8/7
 */
@Slf4j
@RestController
@RequestMapping("/admin/global-water-price-tier")
@Api(tags = "全局阶梯水费配置管理")
public class GlobalWaterPriceTierController {

    @Autowired
    private GlobalWaterPriceTierService globalWaterPriceTierService;

    @GetMapping("/tiers")
    @ApiOperation("获取全局阶梯水费配置")
    public Result getGlobalTiers() {
        try {
            List<GlobalWaterPriceTier> tiers = globalWaterPriceTierService.getActiveTiers();
            return new Result(CodeConstant.SUCCESS, "获取全局阶梯水费配置成功", tiers);
        } catch (Exception e) {
            log.error("获取全局阶梯水费配置失败", e);
            return new Result(CodeConstant.FAIL, "获取全局阶梯水费配置失败: " + e.getMessage());
        }
    }

    @PostMapping("/tiers")
    @ApiOperation("保存全局阶梯水费配置")
    public Result saveGlobalTiers(@RequestBody List<GlobalWaterPriceTier> tiers) {
        try {
            globalWaterPriceTierService.saveGlobalTiers(tiers);
            return new Result(CodeConstant.SUCCESS, "全局阶梯水费配置保存成功", null);
        } catch (Exception e) {
            log.error("保存全局阶梯水费配置失败", e);
            return new Result(CodeConstant.FAIL, "保存全局阶梯水费配置失败: " + e.getMessage());
        }
    }

    @PostMapping("/calculate")
    @ApiOperation("计算全局阶梯水费")
    public Result calculateGlobalTieredPrice(@RequestParam BigDecimal usageAmount) {
        try {
            BigDecimal amount = globalWaterPriceTierService.calculateGlobalTieredPrice(usageAmount);
            return new Result(CodeConstant.SUCCESS, "计算全局阶梯水费成功", amount);
        } catch (Exception e) {
            log.error("计算全局阶梯水费失败", e);
            return new Result(CodeConstant.FAIL, "计算全局阶梯水费失败: " + e.getMessage());
        }
    }

    @PostMapping("/initialize")
    @ApiOperation("初始化默认全局阶梯水费配置")
    public Result initializeDefaultTiers() {
        try {
            globalWaterPriceTierService.initializeDefaultTiers();
            return new Result(CodeConstant.SUCCESS, "初始化默认全局阶梯水费配置成功", null);
        } catch (Exception e) {
            log.error("初始化默认全局阶梯水费配置失败", e);
            return new Result(CodeConstant.FAIL, "初始化默认全局阶梯水费配置失败: " + e.getMessage());
        }
    }
}